package com.greenx.hello;

public class VINChecker {

	public static void main(String[] args) {
		// String vin = "";

		// TODO delete the following script if the complex of code for now
		// is okay
		/**
		 * // number if (flag && (c >= '0' && c <= '9')) { flag = false; } else
		 * if (!flag && (!(c >= '0' && c <= '9'))) { flag = true; }
		 * 
		 */
	}

	/**
	 * 
	 * @param vin
	 * @return
	 */
	public final boolean checkVin(String vin) {
		boolean inValid = false;

		int[] values = { 1, 2, 3, 4, 5, 6, 7, 8, 0, 1, 2, 3, 4, 5, 0, 7, 0, 9,
				2, 3, 4, 5, 6, 7, 8, 9 };
		int[] weights = { 8, 7, 6, 5, 4, 3, 2, 10, 0, 9, 8, 7, 6, 5, 4, 3, 2 };

		String s = vin;
		s = s.replaceAll("-", "");
		s = s.toUpperCase();
		if (s.length() != 17)
			throw new RuntimeException("VIN number must be 17 characters");

		int sum = 0;
		for (int i = 0; i < 17; i++) {
			char c = s.charAt(i);
			int value;
			int weight = weights[i];

			// letter
			if (c >= 'A' && c <= 'Z') {
				value = values[c - 'A'];
				if (value == 0)
					throw new RuntimeException("Illegal character: " + c);
			}

			// number
			else if (c >= '0' && c <= '9')
				value = c - '0';

			// illegal character
			else
				throw new RuntimeException("Illegal character: " + c);

			sum = sum + weight * value;

		}

		// check digit
		sum = sum % 11;
		char check = s.charAt(8);
		if (check != 'X' && (check < '0' || check > '9'))
			inValid = false;
		if (sum == 10 && check == 'X')
			inValid = true;
		else if (sum == check - '0')
			inValid = true;
		else
			inValid = false;

		return inValid;
	}

}
